<?php

namespace app\middleware;

use app\model\AdminPermissions;
use app\model\AdminRolePermissions;
use app\model\AdminRoleUsers;
use http\Env\Response;
use think\facade\Request;


class PermissionMiddleware
{
    public function handle($request, \Closure $next)
    {
        $userId = Request::param('user_id');

        // 获取用户的角色
        $roleIds = AdminRoleUsers::where('user_id', $userId)->column('role_id');

        // 获取角色对应的权限ID
        $permissionIds = AdminRolePermissions::whereIn('role_id', $roleIds)->column('permission_id');

        // 获取权限信息
        $permissions = AdminPermissions::whereIn('id', $permissionIds)->select();

        // 检查当前请求是否有权限
        $currentMethod = Request::method();
        $currentPath = Request::pathinfo();
        foreach ($permissions as $permission) {
            if ($permission->http_method === $currentMethod && $permission->http_path === $currentPath) {
                return $next($request);
            }
        }

        return Response::create(['message' => '没有权限访问'], 403);
    }

    private function checkPermission($permission, $path, $method)
    {
        // Check HTTP method
        if (isset($permission['http_method']) && !empty($permission['http_method'])) {
            $allowedMethods = explode(',', strtoupper($permission['http_method']));
            if (!in_array(strtoupper($method), $allowedMethods)) {
                return false;
            }
        }

        // Check path patterns
        $paths = explode("\n", $permission['http_path']);
        foreach ($paths as $pattern) {
            $pattern = trim($pattern);
            if ($this->matchPath($pattern, $path)) {
                return true;
            }
        }

        return false;
    }

    private function matchPath($pattern, $path)
    {
        $pattern = preg_quote($pattern, '#');
        $pattern = str_replace('\*', '.*', $pattern);
        return preg_match('#^' . $pattern . '$#i', $path);
    }
}